package com.chhuang.component;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.chhuang.constants.MConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;

/**
 * @ClassName UrlLocaleResolver
 * @Description 自己定义区域信息解析器，如果地址栏带l信息，如?l=en_US，就以地址栏为准，
 * 否则以头部信息中的accept-lang为准
 * @Author Darren Huang
 * @Date 2022/11/20 22:58
 * @Version 1.0
 */
@Slf4j
@Component("localeResolver")
public class UrlLocaleResolver implements LocaleResolver {

    private static final Locale LOCALE_CN = new Locale("zh", "CN");
    private static final Locale LOCALE_US = new Locale("en", "US");
    public static final Locale DEFAULT_LACALE = LOCALE_US;
    public static final String DEFAULT_LANGUAGE = DEFAULT_LACALE.getLanguage().substring(0,2).toLowerCase(Locale.ROOT);

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(MConstants.SESSION_SELECTED_LANGUAGE_KEY);
        String lang = request.getParameter("l");
        Locale locale = null;
        try {
            if (StrUtil.isNotBlank(lang) && lang.length() >= 2) {//地址栏存在语言信息
                locale = new Locale(lang.substring(0, 2));
            } else if (obj != null) {// session中用户选择的语言
                lang = (String) obj;
                locale = new Locale(lang);
            } else {//从request获取语言信息
                Locale requestLocale = request.getLocale();
                if (requestLocale != null) {
                    lang = requestLocale.toLanguageTag();
                    if (StrUtil.isNotBlank(lang) && lang.length() >= 2) {
                        locale = new Locale(lang.substring(0, 2));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (locale == null) {
            locale = DEFAULT_LACALE;
        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

}
